﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xdb_Maker.xdb;

namespace xdb_Maker
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "ip2region-xdb-maker@1.0 by woodyfar";
            string srcFile = AppDomain.CurrentDomain.BaseDirectory + "ip.merge.txt";
            string dstFile = AppDomain.CurrentDomain.BaseDirectory + "ip2region.xdb";

            Console.WriteLine(">>本工具引用了作者[Alan Lee]提供的源码。");
            Console.WriteLine(">>本工具源码地址：https://gitee.com/woodyfar/xdb-maker");
            Console.WriteLine(">>引用的源码地址：https://gitee.com/lionsoul/ip2region/tree/master/maker/csharp");
            Console.WriteLine("");
            if (!File.Exists(srcFile))
            {
                ConsoleWriteLine("程序目录下不存在源文件：ip.merge.txt", ConsoleColor.Yellow);
                Console.ReadLine();
                return;
            }
            Console.WriteLine("请选择索引策略[IndexPolicy]（输入对应的序号并按回车确定开始执行）");
            Console.WriteLine("1. VectorIndexPolicy （默认）");
            Console.WriteLine("2. BTreeIndexPolicy");
            string line = Console.ReadLine();

            Console.WriteLine($"开始生成 ip2region.xdb ");
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            IndexPolicy indexPolicy = line == "1" ? IndexPolicy.VectorIndexPolicy : IndexPolicy.BTreeIndexPolicy;

            try
            {
                Maker maker = new Maker(indexPolicy, srcFile, dstFile);
                maker.Init();
                maker.Build();
                stopwatch.Stop();
                Console.WriteLine("");
                ConsoleWriteLine($"生成完毕, 总耗时:{stopwatch.Elapsed.TotalMinutes}分钟", ConsoleColor.Green);
            }
            catch (Exception ex)
            {
                stopwatch.Stop();
                Console.WriteLine("");
                ConsoleWriteLine($"生成过程发生异常：{ex}", ConsoleColor.Red);
            }
            finally
            {
                Console.ReadKey();
            }
        }

        public static void ConsoleWriteLine(string content, ConsoleColor color)
        {
            Console.ForegroundColor = color;
            Console.WriteLine(content);
            Console.ResetColor();
        }
    }
}
